﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraBars.Docking;
using Microsoft.Expression.Encoder.Devices;
using Microsoft.Expression.Encoder.Live;
using Microsoft.Expression.Encoder;
using System.Runtime.InteropServices;
using System.Diagnostics;
using DTO;
using BLL;
using System.IO;

namespace GaraOto
{
    public partial class frmInputManager : DevExpress.XtraEditors.XtraForm
    {
        /// <summary>
        /// Creates job for capture of live source
        /// </summary>
        private LiveJob _job;

        /// <summary>
        /// Device for live source
        /// </summary>
        private LiveDeviceSource _deviceSource;
        EncoderDevice video = null;
        EncoderDevice audio = null;
        Boolean checkConfig = false;
        string videoDevice = null;
        string audioDevice = null;

        TypeBLL typeBLL = new TypeBLL();
        CardBLL cardBLL = new CardBLL();
        public frmInputManager()
        {
            InitializeComponent();
            FillDataComboboxType();
        }

        public void FillDataComboboxType()
        {
            List<TypeDTO> list = typeBLL.FillDataCombobox();
            cbeTypeName.Properties.Items.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                cbeTypeName.Properties.Items.Add(list[i].TypeName);
            }
            cbeTypeName.SelectedIndex = -1;

        }

        private void Reset()
        {
            teCardID.EditValue = null;
            cbeTypeName.SelectedIndex = -1;
            cbeCardStatus.SelectedIndex = -1;
            tePlate.Text = "";
        }


        private void frmInputManager_Load(object sender, EventArgs e)
        {
            if (video == null && audio == null && videoDevice == null && audioDevice == null)
            {
                frmSetting frmSet = new frmSetting();
                frmSet.ShowDialog(this);
            }
            else
            {
                Begin();
            }
        }

        public void Begin()
        {
            video = frmSetting.video;
            audio = frmSetting.audio;
            checkConfig = frmSetting.checkConfig;
            videoDevice = frmSetting.videoDevice;
            audioDevice = frmSetting.audioDevice;
            StopJob();

            if (video == null)
            {
                return;
            }

            // Starts new job for preview window
            _job = new LiveJob();

            // Checks for a/v devices
            if (video != null && audio != null && videoDevice != null && audioDevice != null)
            {
                // Create a new device source. We use the first audio and video devices on the system
                _deviceSource = _job.AddDeviceSource(video, audio);

                // Is it required to show the configuration dialogs ?
                if (checkConfig)
                {
                    // Yes
                    // VFW video device ?
                    if (videoDevice.EndsWith("(VFW)", StringComparison.OrdinalIgnoreCase))
                    {
                        // Yes
                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VfwFormatDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VfwFormatDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VfwSourceDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VfwSourceDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VfwDisplayDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VfwDisplayDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                    }
                    else
                    {
                        // No
                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VideoCapturePinDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VideoCapturePinDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VideoCaptureDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VideoCaptureDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VideoCrossbarDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VideoCrossbarDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VideoPreviewPinDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VideoPreviewPinDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }

                        if (_deviceSource.IsDialogSupported(ConfigurationDialog.VideoSecondCrossbarDialog))
                        {
                            _deviceSource.ShowConfigurationDialog(ConfigurationDialog.VideoSecondCrossbarDialog, (new HandleRef(panelVideoPreview, panelVideoPreview.Handle)));
                        }
                    }
                }
                else
                {
                    // No
                    // Setup the video resolution and frame rate of the video device
                    // NOTE: Of course, the resolution and frame rate you specify must be supported by the device!
                    // NOTE2: May be not all video devices support this call, and so it just doesn't work, as if you don't call it (no error is raised)
                    // NOTE3: As a workaround, if the .PickBestVideoFormat method doesn't work, you could force the resolution in the 
                    //        following instructions (called few lines belows): 'panelVideoPreview.Size=' and '_job.OutputFormat.VideoProfile.Size=' 
                    //        to be the one you choosed (640, 480).
                    _deviceSource.PickBestVideoFormat(new Size(640, 480), 15);
                }

                // Get the properties of the device video
                SourceProperties sp = _deviceSource.SourcePropertiesSnapshot();

                // Resize the preview panel to match the video device resolution set
                panelVideoPreview.Size = new Size(sp.Size.Width, sp.Size.Height);

                // Setup the output video resolution file as the preview
                _job.OutputFormat.VideoProfile.Size = new Size(sp.Size.Width, sp.Size.Height);

                // Display the video device properties set
                statusStrip.Text = sp.Size.Width.ToString() + "x" + sp.Size.Height.ToString() + "  " + sp.FrameRate.ToString() + " fps";

                // Sets preview window to winform panel hosted by xaml window
                _deviceSource.PreviewWindow = new PreviewWindow(new HandleRef(panelVideoPreview, panelVideoPreview.Handle));

                // Make this source the active one
                _job.ActivateSource(_deviceSource);

                //btnStartStopRecording.Enabled = true;
                //btnGrabImage.Enabled = true;

                statusStrip.Text = "Preview activated";
            }
            else
            {
                // Gives error message as no audio and/or video devices found
                MessageBox.Show("No Video/Audio capture devices have been found.", "Warning");
                statusStrip.Text = "No Video/Audio capture devices have been found.";
            }
            StartRecording();
        }
        void StopJob()
        {
            // Has the Job already been created ?
            if (_job != null)
            {
                // Stop Capturing
                StopRecording();

                // Remove the Device Source and destroy the job
                _job.RemoveDeviceSource(_deviceSource);

                // Destroy the device source
                _deviceSource.PreviewWindow = null;
                _deviceSource = null;
            }
        }

        private void frmInputManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result2 = MessageBox.Show("Bạn muốn đóng cửa sổ này?",
"Cảnh báo",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
            if (result2 == DialogResult.Yes)
            {
                StopJob();
            }
            else
            {
                e.Cancel = true;
            }

        }

        private void StopRecording()
        {
            _job.StopEncoding();
            statusStrip.Text = "";
        }

        private Image GrabImage()
        {
            Stream imageStream = new MemoryStream();
            // Create a Bitmap of the same dimension of panelVideoPreview (Width x Height)
            using (Bitmap bitmap = new Bitmap(panelVideoPreview.Width, panelVideoPreview.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    // Get the paramters to call g.CopyFromScreen and get the image
                    Rectangle rectanglePanelVideoPreview = panelVideoPreview.Bounds;
                    Point sourcePoints = panelVideoPreview.PointToScreen(new Point(panelVideoPreview.ClientRectangle.X, panelVideoPreview.ClientRectangle.Y));
                    g.CopyFromScreen(sourcePoints, Point.Empty, rectanglePanelVideoPreview.Size);
                }

                string strGrabFileName = String.Format("D:\\Snapshot_{0:yyyyMMdd_hhmmss}.jpg", DateTime.Now);
                toolStripStatusLabel1.Text = strGrabFileName;

                bitmap.Save(strGrabFileName, System.Drawing.Imaging.ImageFormat.Jpeg);                
                bitmap.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return Image.FromStream(imageStream);
            }
           
        }
        private void StartRecording()
        {
            // Sets up publishing format for file archival type
            FileArchivePublishFormat fileOut = new FileArchivePublishFormat();

            // Sets file path and name
            fileOut.OutputFileName = String.Format("D:\\WebCam{0:yyyyMMdd_hhmmss}.wmv", DateTime.Now);

            // Adds the format to the job. You can add additional formats as well such as
            // Publishing streams or broadcasting from a port
            _job.PublishFormats.Add(fileOut);

            // Start encoding
            _job.StartEncoding();

            statusStrip.Text = fileOut.OutputFileName;
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            frmSetting frmSet = new frmSetting();
            frmSet.ShowDialog(this);
        }

        private void teCardID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (cardBLL.CheckCard(teCardID.Text.Trim()))
            {
                CardDTO cardDTO = cardBLL.LoadInfoCard(teCardID.Text.Trim());
                cbeCardStatus.SelectedItem = cardDTO.Status;
                cbeTypeName.SelectedItem = cardDTO.TypeName;
                if (!cardDTO.TypeName.Equals("Thẻ lượt"))
                {
                    if (cardDTO.Status.Equals("Hết hạn"))
                    {
                        DialogResult result2 = MessageBox.Show("Thẻ đã hết hạn. Bạn muốn gia hạn ko?",
    "Gia hạn thẻ",
    MessageBoxButtons.YesNoCancel,
    MessageBoxIcon.Question);
                        if (result2 == DialogResult.Yes)
                        {
                            frmMain main = (frmMain)this.Owner;
                            this.WindowState = FormWindowState.Minimized;
                            main.Activate();
                            main.bbtnAddCustomer_Click();
                        }
                        else
                        {
                            Reset();
                        }
                    }
                    if (cardDTO.Status.Equals("Khóa"))
                    {
                        MessageBox.Show("Thẻ đã bị khóa");
                    }
                    if (cardDTO.Status.Equals("Mất thẻ"))
                    {
                        MessageBox.Show("Thẻ đã bị báo mất trước đó");
                    }
                    if (cardDTO.Status.Equals("Khóa"))
                    {
                        MessageBox.Show("Thẻ đã bị khóa");
                    }
                    if (cardDTO.Status.Equals("Sử dụng"))
                    {
                        if (GrabImage() != null)
                        {
                            pePlate.EditValue = GrabImage();
                        }
                    }
                }
                else
                {
                    string message = cardBLL.UpdateCardStatus(teCardID.Text.Trim());
                    if (message.Equals(MessageAction.Success))
                    {
                        pePlate.EditValue = GrabImage();
                    }
                    else
                    {
                        MessageBox.Show("Không thể cập nhật trạng thái thẻ lượt");
                    }
                }

            }
        }

    }
}